import React, { Fragment } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { get as getPath } from 'object-path';
import { Form, Input, Button, Row, Col, Table, Divider, Icon, Menu, message, Modal, Dropdown, Card } from 'antd';
import { TablePagination } from 'vv-frontend-components';
import { formatMessage } from 'umi';
import QueryPage from '@/components/QueryPage';
import Locale from '@/utils/locale';
import LinkTo from '@/components/LinkTo';

import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import { withRoutePage } from '@/utils/enhanceUtils';
import style from './RulesDetail.less';

const { checkCode } = authHelper;

// }))
class Rules extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            delatemodalVisible: false,
            delateId: ''
        };
        this.authCode = new AuthCode(props.route.code).authCode;
    }

    componentDidMount() {
        this.fetchList();
    }

    // 显示modal
    setModalVisible(flag) {
        this.setState({ delatemodalVisible: flag });
    }

    // 点击删除操作
    delateNotice = record => {
        this.setState({ delateId: record.id }, () => {
            this.setState({ delatemodalVisible: true });
        });
    };

    // 创建更多操作的菜单
    createMenu = record => {
        const { route } = this.props;
        const menu = (
            <Menu>
                {checkCode(this.authCode('edit')) && (
                    <Menu.Item key="0">
                        {/* <a
                            onClick={() =>
                                history.push(
                                    `${route.path}/rulesAdd?ruleId=${record.id}&action=edit`
                                )
                            }
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.edit'
                            })}
                        </a> */}
                        <LinkTo
                            to={`${route.path}/rulesAdd`}
                            query={{
                                ruleId: record.id,
                                action: 'edit'
                            }}
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.edit'
                            })}
                        </LinkTo>
                    </Menu.Item>
                )}
                {checkCode(this.authCode('delete')) && (
                    <Menu.Item key="1">
                        <a onClick={this.delateNotice.bind(this, record)}>
                            {formatMessage({
                                id: 'columns.noticeList.action.delete'
                            })}
                        </a>
                    </Menu.Item>
                )}
            </Menu>
        );
        return menu;
    };

    // 获取列表
    fetchList = flag => {
        const { dispatch, rules, form } = this.props;
        const { getFieldsValue } = form;
        const { pagination } = rules;
        const searchData = getFieldsValue().searchName ? getFieldsValue().searchName.replace(/(^\s*)|(\s*$)/g, '') : '';
        dispatch({
            type: 'rules/fetchList',
            payload: {
                searchName: searchData,
                pageNo: flag ? 1 : pagination.current,
                pageSize: pagination.pageSize
            },
            callback: res => {
                if (res.code !== 10000) {
                    message.error(res.msg);
                }
            }
        });
    };

    // 切换页码
    changeTable = async pagination => {
        const {
            dispatch,
            rules: { pagination: curPagination }
        } = this.props;
        await dispatch({
            type: 'rules/setPagination',
            pagination: {
                ...curPagination,
                current: pagination.current
            }
        });
        this.fetchList();
    };

    // 确认删除
    sureDelateRule(delatemodalVisible) {
        const { dispatch } = this.props;
        dispatch({
            type: 'rules/fetchDelate',
            payload: {
                ruleId: getPath(this.state, 'delateId')
            },
            callback: res => {
                if (res.code === 10000) {
                    message.success(res.msg);
                    this.fetchList(true);
                } else {
                    message.error(res.msg);
                    this.fetchList(true);
                }
            }
        });
        this.setState({ delatemodalVisible });
    }

    render() {
        const { form } = this.props;
        const { loading, loadingDelate, dispatch, rules, route } = this.props;
        const { data, pagination } = rules;
        const { getFieldDecorator } = form;
        // 处理menu的权限标识符
        // const showMOdule = [];
        // const getRouterAuthority = (result, pathname) => {
        //     if (result && result.length > 0) {
        //         result.map(item => {
        //             showMOdule.push(item.url);
        //             if (
        //                 item.children !== undefined &&
        //                 item.children !== null &&
        //                 item.children.length > 0
        //             ) {
        //                 getRouterAuthority(item.children, pathname);
        //             }
        //             return showMOdule;
        //         });
        //     }
        //     let showorno = false;
        //     showMOdule.forEach(item => {
        //         if (item === pathname) {
        //             showorno = true;
        //         }
        //     });
        //     if (showorno) {
        //         return true;
        //     }
        //     return false;
        // };
        const columns = [
            {
                title: formatMessage({ id: 'columns.ruleList.title' }),
                key: 'title',
                render: (text, record) => (
                    <div style={{ maxWidth: 300 }}>
                        <p
                            onClick={() => {
                                if (!checkCode(this.authCode('detail'))) return;
                                history.push(`${route.path}/rulesDetail?ruleId=${record.id}`);
                            }}
                            style={{
                                cursor: 'pointer',
                                fontWeight: 'bold',
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis'
                            }}
                        >
                            {record.title}
                        </p>
                        <p
                            style={{
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                fontSize: '14px',
                                color: 'rgba(0,0,0,0.45)'
                            }}
                        >
                            {record.content}
                        </p>
                    </div>
                )
            },
            {
                title: formatMessage({ id: 'columns.ruleList.startTime' }),
                dataIndex: 'startTime',
                key: 'startTime'
            },
            {
                title: formatMessage({ id: 'columns.ruleList.createUser' }),
                dataIndex: 'userName',
                key: 'userName'
            },
            {
                title: formatMessage({ id: 'columns.ruleList.recvCompany' }),
                key: 'recvCompanyName',
                width: 300,
                render: (text, record) => (
                    <div
                        style={{
                            width: '100%',
                            overflow: 'hidden',
                            textOverflow: '-o-ellipsis-lastline',
                            display: '-webkit-box',
                            WebkitLineClamp: '2',
                            flexDirection: 'column',
                            WebkitBoxOrient: 'vertical'
                        }}
                        title={record.recvCompanyName}
                    >
                        {record.recvCompanyName}
                    </div>
                )
            },
            {
                title: formatMessage({ id: 'columns.ruleList.action' }),
                key: 'action',
                render: (text, record) => (
                    <span>
                        <AuthComponent code={this.authCode('detail')}>
                            {/* <a
                                onClick={() =>
                                    history.push(
                                        `${route.path}/rulesDetail?ruleId=${record.id}`
                                    )
                                }
                            >
                                {formatMessage({
                                    id: 'columns.ruleList.action.detail'
                                })}
                            </a> */}
                            <LinkTo
                                to={`${route.path}/rulesDetail`}
                                query={{
                                    ruleId: record.id
                                }}
                            >
                                {formatMessage({
                                    id: 'columns.ruleList.action.detail'
                                })}
                            </LinkTo>
                        </AuthComponent>
                        <AuthComponent code={this.authCode('edit') || this.authCode('delete')}>
                            {record.flag && record.flag === '0' ? <Divider type="vertical" /> : null}
                            {record.flag && record.flag === '0' ? (
                                <Dropdown overlay={() => this.createMenu(record)} trigger={['click']}>
                                    <a className="ant-dropdown-link" href="#">
                                        {formatMessage({
                                            id: 'columns.ruleList.action.more'
                                        })}{' '}
                                        <Icon type="down" />
                                    </a>
                                </Dropdown>
                            ) : null}
                        </AuthComponent>
                    </span>
                )
            }
        ];

        return (
            <Fragment>
                <QueryPage
                    className={style.ruleQuery}
                    form={
                        <Form layout="inline">
                            <Card
                                className={style.rulecard}
                                bordered={false}
                                title={
                                    <Row justify="space-between" type="flex">
                                        <Col>
                                            {formatMessage({
                                                id: 'menu.portal.article.rules'
                                            })}
                                        </Col>
                                        <Col>
                                            <AuthComponent code={this.authCode('add')}>
                                                <Form.Item>
                                                    <div
                                                        style={{
                                                            display: 'flex'
                                                        }}
                                                    >
                                                        <Button
                                                            type="primary"
                                                            style={{
                                                                position: 'relative',
                                                                verticalAlign: 'middle',
                                                                margin: '0 0 0 10px'
                                                            }}
                                                            onClick={() => history.push(`${route.path}/rulesAdd`)}
                                                        >
                                                            {formatMessage({
                                                                id: 'edit.model.add.title'
                                                            })}
                                                        </Button>
                                                    </div>
                                                </Form.Item>
                                            </AuthComponent>
                                        </Col>
                                    </Row>
                                }
                            ></Card>
                            <Row span="24" type="flex">
                                <Col
                                    style={{
                                        marginLeft: 30,
                                        marginRight: 10
                                    }}
                                >
                                    <AuthComponent code={this.authCode('query')}>
                                        <Form.Item>
                                            {getFieldDecorator(
                                                'searchName',
                                                {}
                                            )(
                                                <div style={{ display: 'flex' }}>
                                                    <span
                                                        style={{
                                                            width: '150px',
                                                            height: '34px',
                                                            lineHeight: '34px'
                                                        }}
                                                    >
                                                        {formatMessage({
                                                            id: 'edit.search.label'
                                                        })}
                                                    </span>
                                                    <Input
                                                        placeholder={formatMessage({
                                                            id: 'edit.search.keyword'
                                                        })}
                                                        suffix={
                                                            <Icon
                                                                type="search"
                                                                style={{
                                                                    color: 'rgba(0,0,0,0.15)'
                                                                }}
                                                            />
                                                        }
                                                    />
                                                    <Button
                                                        type="primary"
                                                        style={{
                                                            marginLeft: '10px'
                                                        }}
                                                        onClick={() => {
                                                            this.fetchList(true);
                                                        }}
                                                    >
                                                        {formatMessage({
                                                            id: 'edit.search.btn'
                                                        })}
                                                    </Button>
                                                </div>
                                            )}
                                        </Form.Item>
                                    </AuthComponent>
                                    {/* <AuthComponent code={authCode('add')}>
                                        <Form.Item>
                                            <div style={{ display: 'flex' }}>
                                                <Button
                                                    style={{
                                                        position: 'relative',
                                                        verticalAlign: 'middle',
                                                        margin: '0 0 0 10px'
                                                    }}
                                                    onClick={() =>
                                                        history.push(
                                                            '/notice/article/rules/rulesAdd'
                                                        )
                                                    }
                                                >
                                                    {formatMessage({
                                                        id:
                                                            'edit.model.add.title'
                                                    })}
                                                </Button>
                                            </div>
                                        </Form.Item>
                                    </AuthComponent> */}
                                </Col>
                            </Row>
                        </Form>
                    }
                    table={
                        <Table
                            columns={columns}
                            dataSource={data}
                            rowKey="id"
                            loading={loading}
                            style={{ background: '#fff' }}
                            onChange={this.changeTable}
                            pagination={{
                                ...pagination,
                                showTotal: total => (
                                    <TablePagination
                                        itemsName={Locale.set('items')}
                                        total={total}
                                        pageSize={pagination.pageSize}
                                        onChange={async pageSize => {
                                            await dispatch({
                                                type: 'rules/setPagination',
                                                pagination: {
                                                    ...pagination,
                                                    pageSize,
                                                    current: 1
                                                }
                                            });
                                            this.fetchList();
                                        }}
                                    />
                                )
                            }}
                        />
                    }
                />
                <Modal
                    title={formatMessage({
                        id: 'edit.model.ruledelate.title'
                    })}
                    confirmLoading={loadingDelate}
                    wrapClassName="vertical-center-modal"
                    visible={getPath(this.state, 'delatemodalVisible')}
                    onOk={() => this.sureDelateRule(false)}
                    onCancel={() => this.setModalVisible(false)}
                    centered
                >
                    <p>
                        {formatMessage({
                            id: 'edit.model.delate.rulemessage'
                        })}
                    </p>
                </Modal>
            </Fragment>
        );
    }
}
export default withRoutePage(
    connect(({ rules, loading }) => ({
        rules,
        loading: loading.models.rules,
        loadingDelate: loading.effects['rules/fetchDelate']
    }))(Form.create()(Rules))
);
